package it.codelair.services;

import it.codelair.getter.Getter;
import it.codelair.getter.GetterInterface;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

public class Servizio extends Service{
	
	private Timer timer; 
	private Getter getter;
	private Handler handler = new Handler();
	private Runnable runnable=null;
	private static final long PAUSE_TIME=5000;
	
	@Override
	public IBinder onBind(Intent arg0) {
		
		return null;
	}
	

	@Override
	public void onCreate() { 
	   super.onCreate(); 
	   this.getter=new Getter(this);
	  /* 
	  TimerTask task = new TimerTask() { 
		    @Override
		    public void run() { 	
		    
		    	Task thread=new Task();
		    	thread.execute(getter);
		    	
		    	
		   } 
	  }; 
	   timer = new Timer(); 
	   timer.schedule(task, 0, 10000); */
	   Log.d(this.getClass().getName(),"Service started, runnable starting");
	   runnable = new Runnable() {
		   @Override
		   public void run() {
		      /* do what you need to do */
			  Task thread=new Task();
		      thread.execute(getter);
		      /* and here comes the "trick" */
		      handler.postDelayed(this, PAUSE_TIME);
		   }
		};
		handler.postDelayed(runnable, 100);//eseguo il runnable
	 }
	
	
	@Override
	public void onDestroy() { 
		if(handler!=null && runnable!=null)
		{
			Log.d(this.getClass().getName(),"Service stopping, runnable stopping");
			handler.removeCallbacks(runnable);//chiudo handler	
		 }
		
		Log.d(this.getClass().getName(),"Service stopping, runnable stopped");
		super.onDestroy(); 
		Log.d(this.getClass().getName(),"Service stopped");
	    
	   //timer.cancel(); 
	   //timer = null; 
	 } 

}
